package com.blackhorse.publish_subscribe;

import com.blackhorse.utils.ConnectionUtils;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * 发布与订阅使用的交换机类型为：fanout
 */
public class Producer {

    public static final String FANOUT_EXCHANGE = "fanout_exchange";
    public static final String FANOUT_QUEUE_1 = "fanout_queue_1";
    public static final String FANOUT_QUEUE_2 = "fanout_queue_2";

    public static void main(String[] args) {
        Connection connection = null;
        Channel channel = null;
        try {
            connection = ConnectionUtils.getConnection();
            channel = connection.createChannel();
            //声明交换机：
            channel.exchangeDeclare(FANOUT_EXCHANGE, //交换机名称
                    BuiltinExchangeType.FANOUT //交换机类型，fanout、topic、direct、headers
            );
            //声明队列
            channel.queueDeclare(FANOUT_QUEUE_1, true, false, false, null);
            channel.queueDeclare(FANOUT_QUEUE_2, true, false, false, null);
            //队列绑定交换机
            channel.queueBind(FANOUT_QUEUE_1, FANOUT_EXCHANGE, "");
            channel.queueBind(FANOUT_QUEUE_2, FANOUT_EXCHANGE, "");
            for (int i = 0; i < 10; i++) {
                String msg = "你好，小兔子！发布订阅模式，第" + i + "条消息";
                channel.basicPublish(FANOUT_EXCHANGE,//交换机名称，如果没有则使用默认Default Exchange
                        "",//路由key，简单模式可以传递队列名称
                        null,//消息其他属性
                        msg.getBytes());//消息内容
                System.out.println("已发送消息：" + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            ConnectionUtils.close(channel, connection);
        }
    }
}
